<?php

class Sys_Extensions
{
	function __construct() {
		$this->db = Zend_Registry::get("db");
	}

    function RandomSerialNumber($length)
    {
        $code = 'AaBbCcDeEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';

        $rand = $code[rand(0,50)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));

        for(
            $a = md5( $rand, true ),
            $s = '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVv',
            $d = '',
            $f = 0;
            $f < $length;
            $g = ord( $a[ $f ] ),
            @$d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return $d;
    }

    function GetContractsCode($exchange_code, $dig)
    {
        if($dig++ < 10)
        {

            $mod_couponss = new Db_Tables_Coupons();

            $row = $mod_couponss->fetchRow("coupon_code='".$exchange_code."'");

            if(isset($row->coupon_code))
            {
                $i = 8;
                if($dig > $i)
                {
                    $i = $dig;
                }
                $exchange_code = $this->RandomSerialNumber($i);
                $this->GetContractsCode($exchange_code, $dig);
            }
            else
            {
                return $exchange_code;
            }
        }
        else
        {
            return $exchange_code;
        }
    }

    function FormatArray($array)
	{
		if(is_array($array))
		{
			echo "<pre>";
			print_r($array);
			echo "<pre>";
		}else{
			echo "Not an array.";
		}
	}
	
	function TurnMsgToObj($post_str)
	{
		if(!empty($post_str))
		{
			$result = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
		}else{
			$result = NULL;
		}
		
		return $result;
	}
	
	function WelcomeMsg($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$mod_params = new Db_Tables_Params();
		$wechat_welcome_info = $mod_params->WechatWelcomeInfo();
		
		//make relation for recommendation start
		if($postObj->EventKey)
		{
			$mod_subscribe = new Db_Tables_LogsSubscribe();
			$mod_subscribe->key = $postObj->EventKey;
			$mod_subscribe->open_id = $toUser;
			$mod_subscribe->AddRecord();
		}
		//make relation for recommendation end
		
		$items = '';
		
		$num = 0;
		
		for($n=1;$n<6;$n++)
		{
			if($wechat_welcome_info['wechat-welcome-'.$n])
			{
				$items .= "<item>
						<Title><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-title']."]]></Title> 
						<Description><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-desc']."]]></Description>
						<PicUrl><![CDATA[".$wechat_welcome_info['SYS_DOMAIN'].$wechat_welcome_info['wechat-welcome-'.$n.'-picture']."?".date("s")."]]></PicUrl>
						<Url><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-url']."]]></Url>
						</item>";
				
				$num += 1;
			}
		}
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[news]]></MsgType>
						<ArticleCount>".$num."</ArticleCount>
						<Articles>".$items."</Articles></xml>";
		
		return $result;
	}
	
	function QiangQuan($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$contents = "直播啦，品日料玩抽奖劲爆嗨翻天，点击下方抽奖链接秒传送http://m.grouplus.com/I3tULC";
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml>";
		
		return $result;
	}
	
	function ShareMe($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$contents = "ceshi";
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml><xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml>";
		
		return $result;
	}
	
	function SendVcode($cellphone)
	{
		//create vcode
		$mod_veri = new Db_Tables_CellphoneVerification();
		$vcode = $mod_veri->AddVcode($cellphone);
		
		//send sms
		$send_result = $this->SendVerifyCode($cellphone, $vcode);
		return $send_result;
	}
	
	function SendVerifyCode($target_num, $verify_code)
	{
		$result = array(
			'result' => 0,
			'reason' => "未知错误"
		);
		
		$mod_params = new Db_Tables_Params();
		$ytx_info = $mod_params->YtxInfo();
		
		$to = $target_num;
		$datas = array($verify_code,'30');
		$tempId = $ytx_info['ytx-phoneVerify-tempId'];
		
		$accountSid = $ytx_info['ytx-accountSid'];
		$accountToken = $ytx_info['ytx-accountToken'];
		$appId = $ytx_info['ytx-appId'];
		$serverIP = 'app.cloopen.com';
		$serverPort = '8883';
		$softVersion = '2013-12-26';
		
		// 初始化REST SDK
		$rest = new Sys_SmsYtx($serverIP,$serverPort,$softVersion);
		$rest->setAccount($accountSid,$accountToken);
		$rest->setAppId($appId);

		// 发送模板短信
		$sms_result = $rest->sendTemplateSMS($to,$datas,$tempId);
		if($sms_result == NULL ) {
			$result['reason'] = "调用接口失败";
		}
		if($sms_result->statusCode!=0) {
			$result['reason'] = "Error:(".$sms_result->statusCode.")".$sms_result->statusMsg;
			//TODO 添加错误处理逻辑
		}else{
			$result = array(
				'result' => 1,
				'reason' => "发送成功"
			);
		}
	
		return $result;
	}
	
	function Broadcast($url, $data_array, $type) //type=1 POST type=2 GET
	{
		$str_array = array();
		
		$data_str = Zend_Json::encode($data_array);
		
		if(1 == $type)
		{
			$type_txt = "POST";
		}else{
			$type_txt = "GET";
		}
		
		$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		
    	if (curl_errno($ch)) {
    		echo 'Errno'.curl_error($ch);
    	}
    	curl_close($ch);
		
		$result = Zend_Json::decode($tmpInfo);
		
		return $result;
	}
	
	function get_redirect_url($url, $referer="", $timeout = 10) {
		$redirect_url = false;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
		curl_setopt($ch, CURLOPT_NOBODY, TRUE);//不返回请求体内容
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		   'Accept: */*',
		   'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)',
		   'Connection: Keep-Alive'));
		if ($referer) {
		  curl_setopt($ch, CURLOPT_REFERER, $referer);//设置referer
		}

		$content = curl_exec($ch);
		if(!curl_errno($ch)) {
		  $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址
		}

		return $redirect_url;
	 }
	 
	function RevertShortTaobaoUrl($url)
	{
		$result = false;
		
		if($url)
		{
			$long_url = $this->get_redirect_url($url);
			$tu_url = $this->get_redirect_url($long_url);

			$ex = explode("=", $tu_url);
			$link = urldecode($ex[1]);

			$result = $this->get_redirect_url($link, $tu_url);
		}
		
		return $result;
	}
	
	function FormatStandartTaobaoUrl($url)
	{
		$result = array(
			'url' => false,
			'taobao_id' => false,
			'platform' => false
		);
		
		if($url)
		{
			$ex = explode("s.click", strtolower($url));
			
			if(2 == count($ex)) //short link
			{
				$url = $this->RevertShortTaobaoUrl($url);
			}
			
			$result = $this->RemoveUselessParamsFromTaobaoUrl($url);
		}
		
		return $result;
	}
	
	function RemoveUselessParamsFromTaobaoUrl($url)
	{
		$result = array(
			'url' => false,
			'taobao_id' => false,
			'platform' => false
		);
		
		if($url)
		{
			$ex = explode("?", $url);
			
			if(2 == count($ex))
			{
				if (preg_match("/taobao/i", $ex[0])) {
					$platform = 1; //taobao
				} else {
					$platform = 2; //tmall
				}
				
				$ex2 = explode("&", $ex[1]);
				
				if(count($ex2))
				{
					foreach($ex2 as $params)
					{
						$ex3 = explode("=", $params);
						
						if(2 == count($ex3))
						{
							if("id" == $ex3[0])
							{
								$result = array(
									'url' => $ex[0]."?id=".$ex3[1],
									'taobao_id' => $ex3[1],
									'platform' => $platform
								);
								break;
							}
						}
					}
				}
			}
		}
		
		return $result;
	}
	
	function CheckProductUrlValidation($url)
	{
		$result = array(
			"result" => FALSE,
			"reason" => 1 //未知错误
		);
		
		if($url)
		{
			$url = $this->FormatStandartTaobaoUrl($url);
			
			if($url['taobao_id'])
			{
				$mod_products = new Db_Tables_BjmProducts();
				
				if($mod_products->ProductExist($url['taobao_id']))
				{
					$result["reason"] = 2; //商品已存在
				}else{
					$d4_json = file_get_contents("http://pub.alimama.com/items/search.json?q=".urlencode($url['url']));
					$d4 = Zend_Json::decode($d4_json);

					if(is_array($d4))
					{
						if(1 == count($d4['data']['pageList']) && isset($d4['data']['pageList'][0]))
						{
							$pinfo = $d4['data']['pageList'][0];
							$mod_catindex = new Db_Tables_ParamsCatindex();
							
							$result['result'] = TRUE;
							$result['reason'] = "成功";
							$result['url'] = $url['url'];
							$result['taobao_id'] = $url['taobao_id'];
							$result['platform'] = $url['platform'];
							$result['cid'] = $mod_catindex->GetCid($pinfo['leafCatId']);
							$result['original_price'] = $pinfo['zkPrice'];
							$result['sale_in_30_days'] = $pinfo['biz30day'];
							$result['tk_rate'] = $pinfo['tkRate'];
							$result['tk_type'] = 1;

							if(isset($pinfo['tkSpecialCampaignIdRateMap']))
							{
								if(count($pinfo['tkSpecialCampaignIdRateMap']))
								{
									$tkSpecialCampaignIdRateMap = $pinfo['tkSpecialCampaignIdRateMap'];
									arsort($tkSpecialCampaignIdRateMap);
									foreach($tkSpecialCampaignIdRateMap as $tkey => $tval)
									{
										if(0 < $tval)
										{
											$result['tk_rate'] = $tval;
											$$result['tk_type'] = 2;
//											$campaignId = $tkey;
										}
										break;
									}
								}
							}
						}else{
							$result["reason"] = 4; //接口查无此商品
						}
					}else{
						$result["reason"] = 3; //接口返回出错
					}
				}
			}else{
				$result["reason"] = 6; //商品链接格式有误
			}
		}else{
			$result["reason"] = 5; //关键参数丢失
		}
		
		return $result;
	}
	
	function CheckCouponUrlValidation($url, $original_price, $tk_rate)
	{
		$result = array(
			"result" => FALSE,
			"reason" => 1 //未知错误
		);
		
		if($url && $original_price && $tk_rate)
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$data = curl_exec($ch);
			curl_close($ch);
			
			if(trim($data))
			{
				$regex1="/<div class=\"coupon\-info\".*?>.*?<\/div>/ism"; 
				preg_match($regex1, $data, $matches);
				if($matches[0])
				{
					//coupon value
					$regex2="/<dt>(.*?)元优惠券<\/dt>/ism"; 
					preg_match($regex2, $data, $matches2);
					$coupon_value = trim($matches2[1]);
					
					if($coupon_value > 0)
					{
						$result = array(
							"result" => TRUE,
							"reason" => "成功",
							"coupon_value" => $coupon_value,
							"sale_price" => $original_price - $coupon_value,
							"tk_value" => round(($original_price - $coupon_value) * $tk_rate / 100, 2)
						);

						//coupon remaining
						$regex3="/<dd>剩<span class\=\"rest\">(.*?)<\/span>/ism"; 
						preg_match($regex3, $data, $matches3);
						$coupon_remaining = trim($matches3[1]);
						$result['coupon_remaining_qty'] = $coupon_remaining;

						//coupon used
						$regex4="/已领用<span class\=\"count\">(.*?)<\/span>/ism"; 
						preg_match($regex4, $data, $matches4);
						$coupon_used = trim($matches4[1]);
						$result['coupon_used_qty'] = $coupon_used;

						//min order amount
						$regex5="/<dd>单笔满(.*?)元可用/ism"; 
						preg_match($regex5, $data, $matches5);
						$min_order_amount = trim($matches5[1]);
						$result['coupon_min_amount_to_use'] = $min_order_amount;

						//max coupon qty
						$regex6="/每人限领(.*?)张/ism"; 
						preg_match($regex6, $data, $matches6);
						$max_coupon_qty = trim($matches6[1]);
						$result['coupon_max_use_qty'] = $max_coupon_qty;

						//date start
						$regex7="/有效期:(.*?)至/ism";
						preg_match($regex7, $data, $matches7);
						$date_start = trim($matches7[1]);
						$result['coupon_start_date'] = $date_start;

						//date expired
						$regex8="/至(.*?)<\/dd>/ism";
						preg_match($regex8, $data, $matches8);
						$date_expired = trim($matches8[1]);
						$result['coupon_expired_date'] = $date_expired;
					}else{
						$result['reason'] = 5; //查无此优惠券type2
					}
				}else{
					$result['reason'] = 4; //查无此优惠券type1
				}
			}else{
				$result['reason'] = 3; //获取优惠券信息失败
			}
		}else{
			$result['reason'] = 2; //关键参数丢失
		}
		
		return $result;
	}
	
	/**
	 * 重要，不要轻易更改.从原始字符串中检测是否存在商品链接，截取并转化为标准原始链接，将原始字符串中的相应位置做[[]]标记备日后替换，返回字符串和原始链接
	 */
	function GetProductUrl($txt)
	{
		$result = array(
			"txt" => "",
			"url" => ""
		);
		
		if($txt)	
		{
			$preg = "/(https:\/\/(s|detail|world)\.)(?:[\w]+\.)([a-zA-Z\.]{2,6})([\/\w\.-\?\&]*)*\/?/";
			
			preg_match($preg, $txt, $subject);
			
			if(isset($subject[0]))
			{
				$url = $this->FormatStandartTaobaoUrl($subject[0]);
				
				if($url['url'])
				{
					$result['url'] = $url['url'];
					$result['txt'] = preg_replace($preg, "[[]]", $txt);
				}
			}
		}
		
		return $result;
	}
	
	public function GetPidInfo($pid)
    {	
		$result = array(
			'adzoneid' => 0,
			'siteid' => 0
		);
		
		if($pid)
		{
			$ex = explode("_", $pid);
			
			if($ex[2] && $ex[3])
			{
				$result = array(
					'adzoneid' => $ex[3],
					'siteid' => $ex[2]
				);
			}
		}
		
		return $result;
    }
	
	function GetTaoToken($coupon_link, $product_link, $pid, $short_title)
	{
		$result = array(
			"tao_token" => "",
			"2in1_link" => ""
		);
		
		if($coupon_link && $product_link && $pid && $short_title)
		{
			$long_link = $this->TwoInOneLongLink($coupon_link, $product_link, $pid);
			$result['2in1_link'] = $long_link;
			
			$c = new Sys_Ali_TopClient();
			$c->appkey = '23619432';
			$c->secretKey = 'b48f24853854e36e6717b36c98294847';
			
			$req = new Sys_Ali_Request_WirelessShareTpwdCreateRequest();

			$tpwd_param = array(
				'url' => $long_link,
				'text' => $short_title
			);
			
			$req->setTpwdParam(json_encode($tpwd_param));
			$resp = $c->execute($req);
			
			if(isset($resp->model))
			{
				$result['tao_token'] = $resp->model;
			}
		}
		
		return $result;
	}
	
	function TwoInOneLongLink($coupon_link, $product_link, $pid)
	{
		$result = "";
		
		if($coupon_link && $product_link && $pid)
		{
			$activityId = "";
			
			$product_info = $this->FormatStandartTaobaoUrl($product_link);
			
			$ex1 = explode("?", $coupon_link);
			if(2 == count($ex1))
			{
				$ex2 = explode("&", $ex1[1]);
				
				if(count($ex2))
				{
					foreach($ex2 as $ex2v)
					{
						$ex3 = explode("=", $ex2v);
						
						if(in_array($ex3[0], array("activityId", "activityid", "activity_id")) && $product_info['taobao_id'])
						{
							$activityId = $ex3[1];
							
							if($activityId)
							{
								$result = "https://uland.taobao.com/coupon/edetail?activityId=".$activityId."&itemId=".$product_info['taobao_id']."&pid=".$pid."&dx=1&src=tj_bjmt";
							}
						}
					}
				}
			}
		}
		
		return $result;
	}
	
	function WechatUrlDecolation($url)
	{
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb45529d87242d718&redirect_uri=".urlencode($url)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	}
}